import axios from "axios"
import {getToken,clearToken} from "./index.js"
import router from "@/router/index.js"
const request=axios.create({
    baseURL:'http://geek.itheima.net/v1_0',
    timeout:5000
})
//添加请求拦截器
request.interceptors.request.use((config)=>{
    //添加请求参数
    const token =getToken()
    if(token){
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
    },(error)=>{
        return Promise.reject(error)
    }
)
//添加响应拦截器
request.interceptors.response.use((response)=> {
    // 对响应数据做点什么
    return response.data
  }, (error)=> {
    // token失效跳转到登录页
    if (error.response.status === 401) {
        clearToken()
        router.navigate('/login')
        window.location.reload()
    }
    return Promise.reject(error)
})
export default request